package com.powernode.exception;

import com.alibaba.fastjson2.JSON;
import com.powernode.dto.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常通用处理器，只作用在webflux环境下
 *
 **/
@Component
@Slf4j
//保证优先级低于ResponseStatusException，才能拿到响应状态码
@Order(-1)
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()){
            return Mono.error(ex);
        }
        if (ex instanceof ResponseStatusException){
            response.setStatusCode(((ResponseStatusException) ex).getStatus());
        }
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置日志记录信息
        log.error("错误代码：{}：{}",response.getStatusCode().value(),ex.getMessage());

        Result error = Result.failure(response.getStatusCode().value(), ex.getMessage());
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(error));
        return response.writeWith(Mono.just(buffer));
    }
}
